package tw.cating.karmasaver.plurk.auth;

import tw.cating.karmasaver.Constants;
import tw.cating.karmasaver.R;
import tw.cating.karmasaver.intef.finishListener;
import tw.cating.karmasaver.plurk.plurkApi;
import android.accounts.Account;
import android.accounts.AccountAuthenticatorActivity;
import android.accounts.AccountManager;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class authActivity extends AccountAuthenticatorActivity implements View.OnClickListener{
    public static final String PARAM_CONFIRMCREDENTIALS = "confirmCredentials";
    public static final String PARAM_PASSWORD = "password";
    public static final String PARAM_USERNAME = "username";
	public static final String PARAM_AUTHTOKEN_TYPE = "authToken_type";
	
    private AccountManager mAccountManager;
    private Thread mAuthThread;
    private String mAuthtoken;
    private String mAuthtokenType;
    private plurkApi plurk = null;

//    /**
//     * If set we are just checking that the user knows their credentials; this
//     * doesn't cause the user's password to be changed on the device.
//     */
    private Boolean mConfirmCredentials = false;
//
//    /** for posting authentication attempts back to UI thread */
//    private final Handler mHandler = new Handler();
    private TextView mMessage;
    private String mPassword;
    private EditText mPasswordEdit;
    private Button mBtn_OK;

    /** Was the original caller asking for an entirely new account? */
    protected boolean mRequestNewAccount = false;

    private String mUsername;
    private EditText mUsernameEdit;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		mAccountManager = AccountManager.get(this);
		
		Intent intent = getIntent();
		mAuthtokenType = intent.getStringExtra(PARAM_AUTHTOKEN_TYPE);
        mUsername = intent.getStringExtra(PARAM_USERNAME);
        mPassword = intent.getStringExtra(PARAM_PASSWORD);
        mRequestNewAccount = mUsername == null;
        mConfirmCredentials =
            intent.getBooleanExtra(PARAM_CONFIRMCREDENTIALS, false);
        
        requestWindowFeature(Window.FEATURE_LEFT_ICON);
        
        setContentView(R.layout.login_activity);
        getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
            android.R.drawable.ic_dialog_alert);
        
        mMessage = (TextView) findViewById(R.id.message);
        mUsernameEdit = (EditText) findViewById(R.id.username_edit);
        mPasswordEdit = (EditText) findViewById(R.id.password_edit);
        mBtn_OK = (Button) findViewById(R.id.ok_button);

        mUsernameEdit.setText(mUsername);
        if (mRequestNewAccount == false)
        	mUsernameEdit.setEnabled(false);
        mPasswordEdit.setText(mPassword);
        mMessage.setText(getMessage());
        mBtn_OK.setOnClickListener(this);
        
        plurk = new plurkApi(this);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
        final ProgressDialog dialog = new ProgressDialog(this);
       	dialog.setMessage("Login");
        dialog.setIndeterminate(true);
        dialog.setCancelable(true);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                if (mAuthThread != null) {
                    mAuthThread.interrupt();
                    finish();
                }
            }
        });
        return dialog;
	}
	
    /**
     * Returns the message to be displayed at the top of the login dialog box.
     */
    private CharSequence getMessage() {
        getString(R.string.app_name);
        if (TextUtils.isEmpty(mUsername)) {
            // If no username, then we ask the user to log in using an
            // appropriate service.
            final CharSequence msg =
                getText(R.string.login_activity_newaccount_text);
            return msg;
        }
        if (TextUtils.isEmpty(mPassword)) {
            // We have an account but no password
            return getText(R.string.login_activity_loginfail_text_pwmissing);
        }
        return null;
    }
    
    protected void hideProgress() {
    	dismissDialog(0);
    }
    
    protected void showProgress() {
    	showDialog(0);
    }

	public void onClick(View v) {
		// TODO Auto-generated method stub
        if (mRequestNewAccount) {
            mUsername = mUsernameEdit.getText().toString();
        }
        mPassword = mPasswordEdit.getText().toString();
        if (TextUtils.isEmpty(mUsername) || TextUtils.isEmpty(mPassword)) {
            mMessage.setText(getMessage());
        } else {
            showProgress();
            // Start authenticating...
            mAuthThread = plurk.requestLogin(mUsername, mPassword, mListener);
        }
	}
	
	protected void finishLogin() {
        final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);

        if (mRequestNewAccount) {
            mAccountManager.addAccountExplicitly(account, mPassword, null);
            // Set contacts sync for this account.
            ContentResolver.setSyncAutomatically(account,
                ContactsContract.AUTHORITY, true);
        } else {
            mAccountManager.setPassword(account, mPassword);
        }
        final Intent intent = new Intent();
        mAuthtoken = mPassword;
        intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
        intent
            .putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
        
        if (mAuthtokenType != null
            && mAuthtokenType.equals(Constants.AUTHTOKEN_TYPE)) {
            intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthtoken);
        }
        setAccountAuthenticatorResult(intent.getExtras());
        setResult(RESULT_OK, intent);
        finish();
	}
	
    private finishListener mListener = new finishListener() {

		public void onFinish(int result) {
			// TODO Auto-generated method stub
			hideProgress();
			if (result == plurkApi.LOGINRESULT_SUCCESSED) {
				finishLogin();
			} else {
	            if (mRequestNewAccount) {
	                // "Please enter a valid username/password.
	                mMessage.setText(getText(R.string.login_activity_loginfail_text_both));
	            } else {
	                // "Please enter a valid password." (Used when the
	                // account is already in the database but the password
	                // doesn't work.)
	                mMessage.setText(getText(R.string.login_activity_loginfail_text_pwonly));
	            }
			}
		}
    };
}
